package org.yray.sip.factory;

import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/****
 * A leg xxxx01A
 * B leg xxxx01B1
 * B leg xxxx01B2
 */
@Component
public class IdRuleComponent {
    public final static String LEG_TYPE_A="A";
    public final static String LEG_TYPE_B="B";
    private AtomicInteger cal;
    public IdRuleComponent()
    {
        cal=new AtomicInteger(0);
    }

    /***
     * 原ID获取A leg Id
     * @param id
     * @return
     */
    public String createAIdFromSource(long id)
    {
        return id+String.format("%02d",cal.getAndIncrement()%100)+"A";
    }


    //ID
    public String getIdFromABId(String id)
    {
        if(id.charAt(id.length()-1)=='A')
        {
            return id.substring(0,id.length()-1);
        }
        if(id.charAt(id.length()-3)=='B')
        {
            return id.substring(0,id.length()-3);
        }
        return id;
    }

    public String getIdType(String id)
    {
       return id.charAt(id.length()-1)=='A'?LEG_TYPE_A:LEG_TYPE_B;
    }

    public String createBIdFromAId(String aId)
    {
        if(aId.charAt(aId.length()-1)=='A')
        {
            return aId.substring(0,aId.length()-1)+"B"+String.format("%02d",cal.getAndIncrement()%100);
        }
        return aId;
    }

    public String createBIdFromContextId(String contextId)
    {
        return contextId+"B"+String.format("%02d",cal.getAndIncrement()%100);
    }

    public String getAIdFromAOrBId(String aOrBId)
    {
        if(aOrBId.charAt(aOrBId.length()-3)=='B')
        {
            return aOrBId.substring(0,aOrBId.length()-3)+"A";
        }
        return aOrBId;
    }

    public boolean isALeg(String id)
    {
        return getIdType(id).equals(LEG_TYPE_A);
    }
}
